package service.impl;

import dto.RegisterDTO;
import entity.Students;
import mapper.StudentsMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import service.UserService;
import entity.User;
import mapper.UserMapper;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired private UserMapper mapper;
    @Autowired private StudentsMapper studentsMapper;
    public User getById(Integer id) { return mapper.selectById(id); }
    public List<User> getAll() { return mapper.selectAll(); }
    public int update(User u) {
        u.setUpdatedAt(LocalDateTime.now());
        return mapper.update(u);
    }
    @Override
    public int create(User u) {
        if (u.getUsername() == null || u.getUsername().trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (u.getPassword() == null || u.getPassword().trim().isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }

        // 查重
        User existing = mapper.selectByUsername(u.getUsername());
        if (existing != null) {
            throw new IllegalArgumentException("用户名已被注册");
        }

        u.setCreatedAt(LocalDateTime.now());
        return mapper.insert(u);
    }

    @Override
    public User getByUsername(String username) {
        return mapper.selectByUsername(username);
    }

    public int delete(Integer id) {
        return mapper.delete(id);
    }
    @Override
    @Transactional
    public void register(RegisterDTO dto) {
        // 1. 检查用户名是否存在
        User existing = mapper.selectByUsername(dto.getUsername());
        if (existing != null) {
            throw new IllegalArgumentException("用户名已被注册");
        }

        // 2. 创建新用户
        User user = new User();
        user.setUsername(dto.getUsername());
        user.setPassword(dto.getPassword());
        user.setUserType(0); // 学生
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        mapper.insert(user);  // 插入后会自动回填userId

        // 3. 创建学生信息
        Students student = new Students();
        student.setUserId(user.getUserId());
        student.setStudentId(Integer.parseInt(dto.getStudentId())); // 学号
        student.setName(dto.getName());
        student.setGender(dto.getGender());
        student.setCollege(dto.getCollege());
        student.setDepartment(dto.getDepartment());
        student.setGradeYear(dto.getGradeYear());
        student.setStatus(dto.getStatus());
        student.setCreatedAt(LocalDateTime.now());
        student.setUpdatedAt(LocalDateTime.now());
        studentsMapper.insert(student);
    }
    @Override
    public User findByUsername(String username) {
        return mapper.findByUsername(username); // mapper方法
    }

}